import store from '@/store'
import router from '@/router'

function checkPermission(el, binding) {
  const { value } = binding
  const curAth = store.getters && store.getters.curAth
  const buttons = store.getters && store.getters.buttons
  if (curAth === 'ROLE_ADMIN' || curAth === 'ROLE_DEV') {
    return true
  } else {
    if (value) {
      const test = value.replace(/\'/g, '')
      const permissionRoles = router.currentRoute.name + ':' + test
      const hasPermission = buttons.some(info => {
        return permissionRoles === info
      })

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      el.parentNode && el.parentNode.removeChild(el)
      throw new Error(`need roles! Like v-permission="['admin','editor']"`)
    }
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  }
//   },
//   update(el, binding) {
//     checkPermission(el, binding)
//   }
}
